package com.woyowodaows.base;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.BridgeWebViewClient;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.github.lzyzsd.jsbridge.DefaultHandler;

import com.lzy.okgo.OkGo;
import com.tencent.bugly.crashreport.biz.UserInfoBean;
import com.woyowodaows.R;
import com.woyowodaows.request.InterfaceUrl;
import com.woyowodaows.utils.ActivityManagerUtils;
import com.woyowodaows.utils.CacheUserInfoUtils;
import com.woyowodaows.weight.WebViewProgressBarLoading;


import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Cookie;

/**
 * @author haiwei
 *         webview公共类 所有与H5交互界面可继承
 *         2017/3/9
 */

public abstract class BaseWebViewActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.wb_url)
    protected BridgeWebView wbUrl;
    @BindView(R.id.top_progress)
    WebViewProgressBarLoading top_progress;


    protected ValueCallback<Uri> mUploadMessage;
    protected UserInfoBean userBean;
    protected String url;
    protected String title;
    protected  String    banner;
    protected ArrayList<Cookie> cookie;
    private boolean isContinue = false;
    @Override
    public int getLayoutId() {
        return R.layout.activity_base_webview;
    }

    @Override
    public void initView() {
        super.initView();
        ButterKnife.bind(this);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        url = getIntent().getStringExtra("url");
        title = getIntent().getStringExtra("title");
        banner=getIntent().getStringExtra("banner");
        userBean = null;
        wbUrl.setDefaultHandler(new DefaultHandler());
        wbUrl.setWebViewClient(new MyWebViewClients(mContext, wbUrl));
        wbUrl.setWebChromeClient(new MyWebChromeClient());
        WebSettings webSettings = wbUrl.getSettings();
        webSettings.setUserAgentString(webSettings.getUserAgentString() + "liyouGuoji");
        //设置webview是否支持缩放
        if (banner!=null){
            if (banner.equals("0")){
                webSettings.setBuiltInZoomControls(true);
                webSettings.setUseWideViewPort(true);
                webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
                webSettings.setLoadWithOverviewMode(true);
            }
        }
        webSettings.setSupportZoom(true);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDatabaseEnabled(true);

        String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
        //设置定位的数据库路径
        webSettings.setGeolocationDatabasePath(dir);
        //设置 缓存模式
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        // 开启 DOM storage API 功能
        webSettings.setDomStorageEnabled(true);
        //最重要的方法，一定要设置，这就是出不来的主要原因
        webSettings.setDomStorageEnabled(true);
        webSettings.setGeolocationEnabled(true);
        webSettings.setBlockNetworkImage(false);
        webSettings.setSupportMultipleWindows(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setAppCacheMaxSize(Long.MAX_VALUE);
        webSettings.setPluginState(WebSettings.PluginState.ON_DEMAND);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        //cookie失效通知退出登录
        wbUrl.registerHandler("JSEcho", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                finish();
                ActivityManagerUtils.getInstance().finishAllActivity();
            }
        });

        getWindow().getDecorView().addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                ArrayList<View> outView = new ArrayList<>();
                getWindow().getDecorView().findViewsWithText(outView, "QQ浏览器", View.FIND_VIEWS_WITH_TEXT);
                if (outView != null && outView.size() > 0) {
                    outView.get(0).setVisibility(View.GONE);
                }
            }
        });


    }


    public class MyWebViewClients extends BridgeWebViewClient {

        public MyWebViewClients(Context context, BridgeWebView webView) {
            super(context, webView);
        }

        @Override
        public void telUrl(String url) {
            super.telUrl(url);
            //拨打客服电话号码
            Intent phoneIntent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
            startActivity(phoneIntent);
        }

        //错误页面的逻辑处理
        @Override
        public void onReceivedError(WebView view, int errorCode,
                                    String description, String failingUrl) {
            if (BaseWebViewActivity.this.isFinishing()) {
                return;
            }
            errorOperation();
        }
    }

    public class MyWebChromeClient extends WebChromeClient {

        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String AcceptType, String capture) {
            this.openFileChooser(uploadMsg);
        }

        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String AcceptType) {
            this.openFileChooser(uploadMsg);
        }

        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            mUploadMessage = uploadMsg;
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            if (BaseWebViewActivity.this.isFinishing()) {
                return;
            }
            //如果进度条隐藏则让它显示
            if (View.GONE == top_progress.getVisibility()) {
                top_progress.setVisibility(View.VISIBLE);
            }
            //大于80的进度的时候,放慢速度加载,否则交给自己加载
            if (newProgress >= 80) {
                //拦截webView自己的处理方式
                if (isContinue) {
                    return;
                }
                top_progress.setCurProgress(100, 2500, new WebViewProgressBarLoading.OnEndListener() {
                    @Override
                    public void onEnd() {
                        finishOperation();
                        isContinue = false;
                    }
                });

                isContinue = true;
            } else {
                top_progress.setNormalProgress(newProgress);
            }
        }
    }


    /**
     * 监听返回按钮
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            webBack();
            return true;
        }
        return false;
    }

    /**
     * webview返回
     */
    protected void webBack() {
        if (wbUrl.canGoBack()) {
            wbUrl.goBack();
        } else {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        clearWebViewCache();
    }

    /**
     * 请求web所有缓存
     */
    private void clearWebViewCache() {
        wbUrl.clearHistory();
        wbUrl.clearFormData();
        wbUrl.clearCache(true);
        wbUrl.unregisterHandler();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_get_back:
                webBack();
                break;
        }
    }

    /**
     * 错误的时候进行的操作
     */
    public void errorOperation() {
        if (View.GONE == top_progress.getVisibility()) {
            top_progress.setVisibility(View.VISIBLE);
        }
        //3.5s 加载 0->80 进度的加载 为了实现,特意调节长了事件
        top_progress.setCurProgress(80, 3500, new WebViewProgressBarLoading.OnEndListener() {
            @Override
            public void onEnd() {
                //3.5s 加载 80->100 进度的加载
                top_progress.setCurProgress(100, 3500, new WebViewProgressBarLoading.OnEndListener() {
                    @Override
                    public void onEnd() {
                        finishOperation();
                    }
                });
            }
        });
    }

    /**
     * 结束进行的操作
     */
    private void finishOperation() {
        if (BaseWebViewActivity.this.isFinishing()) {
            return;
        }
        //最后加载设置100进度
        top_progress.setNormalProgress(100);
        hideProgressWithAnim();
    }

    /**
     * 隐藏加载对话框
     */
    private void hideProgressWithAnim() {
        AnimationSet animation = getDismissAnim(mContext);
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                top_progress.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
        top_progress.startAnimation(animation);
    }

    /**
     * 获取消失的动画
     *
     * @param context
     * @return
     */
    private AnimationSet getDismissAnim(Context context) {
        AnimationSet dismiss = new AnimationSet(context, null);
        AlphaAnimation alpha = new AlphaAnimation(1.0f, 0.0f);
        alpha.setDuration(1000);
        dismiss.addAnimation(alpha);
        return dismiss;
    }


    /**
     * 设置cookies到webview
     *
     * @param url
     */
    protected void setCookies(final String url) {
                cookie = (ArrayList<Cookie>) OkGo.getInstance().getCookieJar().getCookieStore().getAllCookie();
                if (cookie == null || cookie.size() == 0) {
                    return;
                }
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                    CookieSyncManager.createInstance(mContext);
                }

                CookieManager cm= CookieManager.getInstance();
                cm.setAcceptCookie(true);
                cm.removeSessionCookie();
                cm.removeAllCookie();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    cm.setAcceptThirdPartyCookies(wbUrl, true);
                }
                cm.setCookie(InterfaceUrl.H5_BASE_URL,cookie.get(cookie.size() - 1).toString());
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                    CookieSyncManager.getInstance().sync();
                } else {
                    CookieManager.getInstance().flush();
                }
    }

}
